package com.atguigu.springcloud.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.springcloud.dto.BurnTaskInfoDto;
import com.atguigu.springcloud.dto.BurnTaskStatusDto;
import com.atguigu.springcloud.service.BurnService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @author xiaolong
 * @version 1.0
 * @description: 监听消息类
 * @date 2021/10/15 17:39
 */
@Component
@Slf4j
@ConditionalOnProperty(value = {"burn.enable"}, havingValue = "true")  //只有当burn.enable=true才会注入bean
public class RabbitmqListener {

    @Autowired
    private BurnService burnService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * @param data 消息数据
     * @return
     * @description: 任务状态接收  定义消费者对象bean singleListenerContainer
     */
    @RabbitListener(queues = "RemoteTrialTaskStatusQueue", containerFactory = "singleListenerContainer")
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(value = "RemoteTrialTaskStatusQueue",durable = "ture",autoDelete = "false"),
//            exchange = @Exchange(value ="BurnDownloadExchange",type = ExchangeTypes.TOPIC),
//            key = "RemoteTrial"
//    ))
    @RabbitHandler
    public void taskStatus(@Payload byte[] data, Message message, Channel channel) {
        long tag = message.getMessageProperties().getDeliveryTag();
        try {
            BurnTaskStatusDto burnTaskStatusDto = objectMapper.readValue(data, BurnTaskStatusDto.class);
            log.info("接收任务状态-{}", JSONObject.toJSONString(burnTaskStatusDto));
            burnService.taskStatus(burnTaskStatusDto);
            //手动设置确认应答  --必须要在定义SimpleRabbitListenerContainerFactory 中将系统默认的自动改为手动
            channel.basicAck(tag, true);
        } catch (IOException e) {
            log.error("执行rabbitmq任务状态接收失败");
        }

    }

}
